package com.sisyphus.spinach.network.presenters;

import com.sisyphus.spinach.core.INetTask;
import com.sisyphus.spinach.network.exceptions.FormException;
import com.sisyphus.spinach.network.utils.Form;

/**
 * 网络表单任务
 *
 * @param <T> 返回数据类型
 * @param <V> 绑定的view
 */
public class FormTask<T, V extends INetTask.View<T>> implements INetTask.Presenter<T, V> {

    public static class Builder<T, V extends INetTask.View<T>> {

        private V mView;

        private Form.Rule[] mFormRules;

        private INetTask.Presenter mNetTask;

        public Builder<T, V> form(Form.Rule... formRules) {
            mFormRules = formRules;
            return this;
        }

        public Builder<T, V> netTask(INetTask.Presenter netTask) {
            mNetTask = netTask;
            return this;
        }

        public Builder<T, V> view(V view) {
            mView = view;
            return this;
        }

        public FormTask<T, V> build() {
            FormTask<T, V> formTask = new FormTask<>(mFormRules);
            formTask.bind(mView);
            formTask.addNetTask(mNetTask);
            return formTask;
        }
    }


    private V mView;

    private INetTask.Presenter mNetTask;

    private final Form.Rule[] mFormRules;

    private FormTask(Form.Rule... formRules) {
        mFormRules = formRules;
    }

    @Override
    public void bind(V view) {
        mView = view;
    }

    public void addNetTask(INetTask.Presenter netTask) {

        mNetTask = netTask;
    }

    @Override
    public void execute() {
        for (Form.Rule rule : mFormRules) {
            if (!rule.validation()) {
                // 失败
                mView.failure(new FormException(rule.getErrorMessage()));
                break;
            }
        }

        // 成功
        mNetTask.execute();
        mView.success(null);
    }

}
